#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
企业微信群机器人核心类
"""

import os
import logging
from typing import Optional

from config.settings import settings
from services.wx_api import WeChatAPI
from services.wx_crypto_service_new import WXBizMsgCrypt
from handlers.message_handler import MessageHandler
from services.wx_api import WeChatAPI

logger = logging.getLogger(__name__)

class WeChatBot:
    """企业微信群机器人核心类"""
    
    def __init__(self):
        self.config = settings
        
        # 初始化企业微信API
        self.wx_api = WeChatAPI()
        
        # 初始化企业微信加密服务
        receive_id = self.config.WX_RECEIVE_ID
        if self.config.WX_TOKEN and self.config.WX_AES_KEY and receive_id:
            try:
                self.wx_crypto = WXBizMsgCrypt(
                    token=self.config.WX_TOKEN,
                    encoding_aes_key=self.config.WX_AES_KEY,
                    receive_id=receive_id
                )
                logger.info("✅ 企业微信加解密服务初始化成功")
            except Exception as e:
                logger.error(f"❌ 企业微信加解密服务初始化失败: {str(e)}")
                self.wx_crypto = None
        else:
            self.wx_crypto = None
            logger.warning("⚠️ 企业微信加解密配置不完整，将使用明文模式")
        
        # 初始化消息处理器
        self.message_handler = MessageHandler(self.wx_api, self.wx_crypto)
        
        # 启动时获取客服账号列表
        self.init_kf_accounts()
    
    def init_kf_accounts(self):
        """初始化时获取客服账号列表"""
        try:
            logger.info("正在获取客服账号列表...")
            accounts_result = self.wx_api.get_kf_accounts()
            if accounts_result:
                account_list = accounts_result.get('account_list', [])
                if account_list:
                    logger.info(f"找到 {len(account_list)} 个客服账号:")
                    for i, account in enumerate(account_list, 1):
                        name = account.get('name', '未知账号')
                        open_kfid = account.get('open_kfid', '未知ID')
                        status = account.get('status', '未知状态')
                        logger.info(f"  {i}. {name} (OpenKfId: {open_kfid}, 状态: {status})")
                        # try:
                        #     api = WeChatAPI()
                        #     print(f"准备调用get_kf_servicers: {open_kfid}")
                        #     logger.error(f"准备调用get_kf_servicers: {open_kfid}")
                        #     servicer_info = api.get_kf_servicers(open_kfid=open_kfid)
                        #     print(f"  {i}. {name} (OpenKfId: {open_kfid}) 的接待人员userid: {servicer_info.get('servicers')}")
                        #     logger.error(f"  {i}. {name} (OpenKfId: {open_kfid}) 的接待人员userid: {servicer_info.get('servicers')}")
                        # except Exception as e:
                        #     print(f"调用get_kf_servicers异常: {e}")
                        #     logger.error(f"调用get_kf_servicers异常: {e}")
                    # 自动设置第一个账号的OpenKfId
                    first_account = account_list[0]
                    first_open_kfid = first_account.get('open_kfid')
                    if first_open_kfid:
                        # 更新环境变量和配置
                        os.environ['KF_ID'] = first_open_kfid
                        self.config.KF_ID = first_open_kfid
                        logger.info(f"自动设置KF_ID为: {first_open_kfid}")
                else:
                    logger.warning("没有找到客服账号")
            else:
                logger.error("获取客服账号列表失败")
        except Exception as e:
            logger.error(f"初始化客服账号时发生错误: {str(e)}")
    
    def verify_url(self, msg_signature: str, timestamp: str, nonce: str, echostr: str) -> Optional[str]:
        """验证URL有效性（企业微信回调配置时使用）"""
        if not self.wx_crypto:
            logger.error("企业微信加解密未配置，无法验证URL")
            return None
            
        try:
            return self.wx_crypto.verify_url(msg_signature, timestamp, nonce, echostr)
        except Exception as e:
            logger.error(f"URL验证失败: {str(e)}")
            return None
    
    def decrypt_message(self, msg_signature: str, timestamp: str, nonce: str, encrypted_msg: str) -> Optional[str]:
        """解密企业微信消息"""
        if not self.wx_crypto:
            logger.error("企业微信加解密未配置，无法解密消息")
            return None
            
        try:
            return self.wx_crypto.decrypt_wechat_message(msg_signature, timestamp, nonce, encrypted_msg)
        except Exception as e:
            logger.error(f"消息解密失败: {str(e)}")
            return None
    
    def parse_xml_message(self, xml_content: str):
        """解析XML格式的企业微信消息"""
        return self.message_handler.parse_xml_message(xml_content)
    
    def call_ai_api(self, message: str, customer_id: str = None) -> str:
        """调用AI API进行智能回复"""
        logger.info(f"=== core/bot.py call_ai_api方法开始 ===")
        logger.info(f"参数: message='{message}', customer_id='{customer_id}'")
        result = self.message_handler.call_ai_api(message, customer_id)
        logger.info(f"=== core/bot.py call_ai_api方法结束，结果: {result} ===")
        return result
    
    def process_message(self, message_data: dict) -> str:
        """处理接收到的消息"""
        try:
            # 解析消息内容
            msg_type = message_data.get('msg_type', '')
            content = message_data.get('content', '').strip()
            from_user = message_data.get('from_user', '')
            
            logger.info(f"收到来自 {from_user} 的 {msg_type} 消息: {content}")
            
            # 处理客服事件
            if msg_type == 'event' and 'kf_msg_or_event' in content:
                logger.info("收到客服事件，正在获取具体消息内容...")
                
                # 立即返回success，避免企业微信重复推送
                # 在后台异步处理消息
                self.message_handler.process_kf_message_async(self.wx_api, self.config)
                
                return "success"
            
            # 只处理文本消息
            if msg_type != 'text':
                return "抱歉，我只支持文本消息。"
            
            if not content:
                return "您好！我是AI助手，有什么可以帮助您的吗？"
            
            # 调用AI API
            response = self.call_ai_api(content)
            logger.info(f"AI回复: {response}")
            
            return response
            
        except Exception as e:
            logger.error(f"处理消息时发生错误: {str(e)}")
            return "抱歉，处理您的消息时出现了问题。"
    
    def process_message_async(self, message_data: dict):
        """异步处理消息"""
        self.message_handler.process_message_async(message_data, self.config.WEBHOOK_URL)
    
    def get_current_timestamp(self) -> str:
        """获取当前时间戳"""
        if self.wx_crypto:
            return self.wx_crypto.get_current_timestamp()
        else:
            import time
            return str(int(time.time())) 